package com.example.aidlclientdemo;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;

import com.example.aidlservicedemo.IPlayListener;
import com.example.aidlservicedemo.ITest;
import com.example.aidlservicedemo.Person;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 主界面
 *
 * @author Jin
 * @since 2021/7/1
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final IPlayListener.Stub mPlayListener = new MyPlayListenerStub();

    private ITest iTest;

    private final MyDeathRecipient deathRecipient = new MyDeathRecipient(this);

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("TAG", "onServiceConnected is running on main thread: " + ThreadUtils.isMainThread());
            iTest = ITest.Stub.asInterface(service);
            try {
                service.linkToDeath(deathRecipient, 0);
            } catch (RemoteException e) {
                Log.i("TAG", "linkToDeath, RemoteException：" + e.getMessage());
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("TAG", "onServiceDisconnected is running on main thread: " + ThreadUtils.isMainThread());
            Log.i("TAG", "onServiceDisconnected");
            iTest = null;
        }
    };

    private static class MyDeathRecipient implements IBinder.DeathRecipient {

        private final WeakReference<MainActivity> mainActivityWeakReference;

        public MyDeathRecipient(MainActivity activity) {
            mainActivityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void binderDied() {
            MainActivity mainActivity = mainActivityWeakReference.get();
            if (mainActivity == null || mainActivity.iTest == null) {
                return;
            }
            mainActivity.iTest.asBinder().unlinkToDeath(this, 0);
            mainActivity.iTest = null;
            Log.i("TAG", "binderDied");
        }

    }

    private AppCompatButton m1Tv;

    private AppCompatButton m2Tv;

    private AppCompatButton m3Tv;

    private AppCompatButton m4Tv;

    private AppCompatButton m5Tv;

    private AppCompatButton m6Tv;

    public static void start(Context context) {
        Intent starter = new Intent(context, MainActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        if (iTest == null) {
            Intent intent = new Intent(ITest.class.getName());
            intent.setAction("service.calc");
            intent.setPackage("com.example.aidlservicedemo");
            boolean isBindService =
                bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
            Log.i("TAG", "isBindService: " + isBindService);
        }
    }

    private void initView() {
        m1Tv = findViewById(R.id.tv_1);
        m2Tv = findViewById(R.id.tv_2);
        m3Tv = findViewById(R.id.tv_3);
        m4Tv = findViewById(R.id.tv_4);
        m5Tv = findViewById(R.id.tv_5);
        m6Tv = findViewById(R.id.tv_6);
        m1Tv.setOnClickListener(this);
        m2Tv.setOnClickListener(this);
        m3Tv.setOnClickListener(this);
        m4Tv.setOnClickListener(this);
        m5Tv.setOnClickListener(this);
        m6Tv.setOnClickListener(this);
        findViewById(R.id.tv_7).setOnClickListener(this);
        findViewById(R.id.tv_8).setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    @Override
    public void onClick(View v) {
        if (iTest != null) {
            try {
                int id = v.getId();
                if (id == R.id.tv_1) {
                    // addNumbers
                    int addNumbers = iTest.addNumbers(11, 13);
                    Log.i("TAG", "addNumbers: " + addNumbers);
                } else if (id == R.id.tv_2) {
                    // getStringList
                    List<String> stringList = iTest.getStringList();
                    Log.i("TAG", "StringList: " + stringList.toString());
                } else if (id == R.id.tv_3) {
                    // getPersonList
                    List<Person> personList = iTest.getPersonList();
                    for (Person person : personList) {
                        Log.i("TAG", "PersonName: " + person.name);
                    }
                } else if (id == R.id.tv_4) {
                    if (!mPlayListener.isBinderAlive()) {
                        Log.i("TAG", "mPlayListener 已经死亡");
                        return;
                    }
                    // placeCall
                    iTest.placeCall("12454567");
                } else if (id == R.id.tv_5) {
                    if (!mPlayListener.isBinderAlive()) {
                        Log.i("TAG", "mPlayListener 已经死亡");
                        return;
                    }
                    // placeCall
                    iTest.involved(mPlayListener);
                } else if (id == R.id.tv_6) {
                    // Messenger使用示例
                    MessengerActivity.start(this);
                } else if (id == R.id.tv_7) {
                    SocketActivity.start(this);
                } else if (id == R.id.tv_8) {
                    BinderPoolActivity.start(this);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private static class MyPlayListenerStub extends IPlayListener.Stub {

        @Override
        public void onSuccess(String name, Bundle bundle) {
            Log.i("TAG", "调用前日志: 即将处理 onSuccess 回调");
            Log.i("TAG", "onSuccess: " + name);
            if (bundle != null) {
                Log.i("TAG", "user: " + bundle.getString("user", "蔡依林"));
                Log.i("TAG", "age: " + bundle.getInt("age", 33));
            }
            Log.i("TAG", "调用后日志: 已完成 onSuccess 回调处理");
        }

    }

}
